package com.dingwen.treasure.business.component.task;

import cn.hutool.extra.spring.SpringUtil;
import com.dingwen.treasure.base.enums.TaskGenerateType;
import com.dingwen.treasure.business.model.dto.TaskGenerateDto;
import com.dingwen.treasure.business.model.entity.TaskGenerate;
import com.dingwen.treasure.business.service.TaskGenerateService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 　AbstractTaskGenerate
 * 　@author dingwen
 * 　@date 2022/8/4
 */
public abstract class AbstractTaskGenerate {

    /**
     * 生成任务类型
     */
    protected TaskGenerateType generateType;


    /**
     * 下一个任务生成处理器
     */
    protected AbstractTaskGenerate nextTaskGenerate;


    /**
     * 设置下一个任务生成处理器
     *
     * @param taskGenerate 任务生成
     */
    public void setNextTaskGenerate(AbstractTaskGenerate taskGenerate) {
        this.nextTaskGenerate = taskGenerate;
    }


    /**
     * 执行
     *
     * @param taskGenerateDTO 任务生成dto
     */
    @Transactional(rollbackFor = Exception.class)
    public void execute(TaskGenerateDto taskGenerateDTO) {
        TaskGenerateService taskGenerateService = SpringUtil.getBean(TaskGenerateService.class);
        if (Objects.equals(generateType, taskGenerateDTO.getTaskGenerateType())) {
            Optional<List<TaskGenerate>> optionalTasks = generate(taskGenerateDTO);
            optionalTasks.ifPresent(tasks -> taskGenerateService.saveBath(tasks));
            return;
        }
        this.nextTaskGenerate.execute(taskGenerateDTO);
    }


    /**
     * 生成
     *
     * @param taskGenerateDTO 任务生成dto
     * @return {@link Optional}<{@link List}<{@link TaskGenerate}>>
     */
    protected abstract Optional<List<TaskGenerate>> generate(TaskGenerateDto taskGenerateDTO);
}
